import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gamma
from sklearn.cluster import DBSCAN
import matplotlib.patches as patches  # 新增，用于绘制矩形


def matern_cluster_process(
    center, radius, num_clusters, lambda_p, mean_cluster_size, gamma_shape
):
    """
    模拟Matern簇过程

    :param center: 圆形区域的中心坐标 (x0, y0)
    :param radius: 圆形区域的半径
    :param num_clusters: 母点（簇中心）的数量
    :param lambda_p: 母点过程的强度
    :param mean_cluster_size: 平均簇大小
    :param gamma_shape: 用于生成簇半径的伽马分布的形状参数
    :return: 模拟得到的所有点的坐标数组，簇中心点的x坐标数组，簇中心点的y坐标数组
    """
    # 生成母点（簇中心）的坐标
    parent_points_x = np.random.uniform(
        center[0] - radius, center[0] + radius, num_clusters
    )
    parent_points_y = np.random.uniform(
        center[1] - radius, center[1] + radius, num_clusters
    )

    all_points = []

    for i in range(num_clusters):
        # 生成簇半径
        cluster_radius = gamma.rvs(gamma_shape)

        # 生成簇内点的数量，假设服从泊松分布
        num_points_in_cluster = np.random.poisson(mean_cluster_size)

        # 生成簇内点的坐标
        points_in_cluster_x = np.random.uniform(
            parent_points_x[i] - cluster_radius,
            parent_points_x[i] + cluster_radius,
            num_points_in_cluster,
        )
        points_in_cluster_y = np.random.uniform(
            parent_points_y[i] - cluster_radius,
            parent_points_y[i] + cluster_radius,
            num_points_in_cluster,
        )

        # 筛选出在圆形区域内的点
        valid_indices = np.where(
            (points_in_cluster_x - center[0]) ** 2
            + (points_in_cluster_y - center[1]) ** 2
            <= radius**2
        )
        valid_points_x = points_in_cluster_x[valid_indices]
        valid_points_y = points_in_cluster_y[valid_indices]

        all_points.extend([(x, y) for x, y in zip(valid_points_x, valid_points_y)])

    return np.array(all_points), parent_points_x, parent_points_y


# 设置参数
center = (0, 0)  # 圆形区域中心坐标
radius = 20  # 圆形区域半径
num_clusters = 20  # 母点（簇中心）数量
lambda_p = 0.5  # 母点过程的强度
mean_cluster_size = 8  # 平均簇大小
gamma_shape = 2  # 用于生成簇半径的伽马分布的形状参数

# 模拟Matern簇过程
points, parent_points_x, parent_points_y = matern_cluster_process(
    center, radius, num_clusters, lambda_p, mean_cluster_size, gamma_shape
)

# 创建一个包含两个子图的窗口
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))

# 在第一个子图中绘制模拟Matern簇过程的图形
ax1.scatter(points[:, 0], points[:, 1], label="All Points")
parent_points = np.array(
    [(parent_points_x[i], parent_points_y[i]) for i in range(num_clusters)]
)
ax1.scatter(
    parent_points[:, 0],
    parent_points[:, 1],
    marker="^",
    s=50,
    c="green",
    label="Cluster Centers",
)
ax1.set_xlim(center[0] - radius, center[0] + radius)
ax1.set_ylim(center[1] - radius, center[1] + radius)
ax1.set_aspect("equal", adjustable="box")
ax1.set_title("Matern Cluster Process")
ax1.set_xlabel("X-axis")
ax1.set_ylabel("Y-axis")
ax1.legend()

# 使用DBSCAN进行聚类
dbscan = DBSCAN(eps=2.5, min_samples=4)  # 这里的参数可根据实际情况调整
clusters = dbscan.fit_predict(points)

# 提取不同簇的点和噪声点
unique_clusters = np.unique(clusters)
cluster_sets = {cluster: [] for cluster in unique_clusters}
for i, cluster_label in enumerate(clusters):
    if cluster_label != -1:
        cluster_sets[cluster_label].append(points[i])
    else:
        cluster_sets[-1] = [] if -1 not in cluster_sets else cluster_sets[-1]
        cluster_sets[-1].append(points[i])

# 在第二个子图中绘制DBSCAN聚类后的图形
for cluster_label, cluster_points in cluster_sets.items():
    if cluster_label != -1:
        ax2.scatter(
            [p[0] for p in cluster_points],
            [p[1] for p in cluster_points],
            label=f"Cluster {cluster_label}",
        )
    else:
        ax2.scatter(
            [p[0] for p in cluster_points],
            [p[1] for p in cluster_points],
            label="Noise Points",
            marker="x",
            c="gray",
        )
parent_points = np.array(
    [(parent_points_x[i], parent_points_y[i]) for i in range(num_clusters)]
)
"""
ax2.scatter(
    parent_points[:, 0],
    parent_points[:, 1],
    marker="^",
    s=50,
    c="green",
    label="Cluster Centers",
)
"""
ax2.set_xlim(center[0] - radius, center[0] + radius)
ax2.set_ylim(center[1] - radius, center[1] + radius)
ax2.set_aspect("equal", adjustable="box")
ax2.set_title("Matern Cluster Process with DBSCAN Clustering")
ax2.set_xlabel("X-axis")
ax2.set_ylabel("Y-axis")
# ax2.legend(loc="upper right", fontsize="small")


# 标注willie
ax1.scatter(0, 0, marker="+", s=100, c="r", label="Willie")

ax2.scatter(0, 0, marker="+", s=100, c="r", label="Willie")

# 划定GZ区域
"""
# 设定半径
circle_radius = 5

# 绘制以原点为圆心的圆
circle1 = plt.Circle((0, 0), circle_radius, fill=False, color="black")
ax1.add_patch(circle1)
circle2 = plt.Circle((0, 0), circle_radius, fill=False, color="black")
ax2.add_patch(circle2)

# 判断点是否在圆内
in_circle = (points[:, 0] - 0) ** 2 + (points[:, 1] - 0) ** 2 <= circle_radius**2

# 将圆内的点变红
ax2.scatter(points[in_circle, 0], points[in_circle, 1], c="red")
"""

# 新增逻辑，以0.5的概率在所有点位置放置黑色正方形
square_size = 0.5  # 正方形边长，可以根据需求调整大小
for point in points:
    if np.random.rand() < 0.2:  # 以0.5的概率决定是否绘制正方形
        # 为ax1创建矩形对象并添加
        rect1 = patches.Rectangle(
            (point[0] - square_size / 2, point[1] - square_size / 2),
            square_size,
            square_size,
            linewidth=1,
            edgecolor="black",
            facecolor="none",
        )
        ax1.add_patch(rect1)
        # 为ax2创建矩形对象并添加
        rect2 = patches.Rectangle(
            (point[0] - square_size / 2, point[1] - square_size / 2),
            square_size,
            square_size,
            linewidth=1,
            edgecolor="black",
            facecolor="none",
        )
        ax2.add_patch(rect2)
plt.show()
